package cn.skcks.springboot03.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Locale;

// 扩展 SpringMVC
// @EnableWebMvc    // 若添加此注解 则 全面接管 Spring MVC 的配置, 即 Spring Boot 默认的 MVC 自动配置失效
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
	// 视图跳转
	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		// 重定向
		registry.addRedirectViewController("/", "/index");

		registry.addViewController("/test").setViewName("index");
	}

	@Bean
	public ViewResolver myViewResolver() {
		return new MyViewResolver();
	}

	// 自定义视图解析器
	public static class MyViewResolver implements ViewResolver {
		@Override
		public View resolveViewName(String viewName, Locale locale) throws Exception {
			return null;
		}
	}

	// 注册到 spring 容器中
	@Bean
	public LocaleResolver localeResolver() {
		return new MyLocaleResolver();
	}

	// 添加拦截器
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new MyHandlerInterceptor())
				.addPathPatterns("/**") // 拦截的路径
				.excludePathPatterns("/favicon.ico","/js/**", "/webjars/**", "/css/**"); // 排除的路径
	}
}